package com.tul.vapp.servicecenter.client;

import java.util.Map;

import com.tul.vapp.servicecenter.common.ZkNodeConstant;
import com.tul.cusa.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tul.vapp.servicecenter.common.CharSetConstant;
import com.tul.vapp.servicecenter.common.StatusEnum;
import com.tul.vapp.servicecenter.utils.ConfigUtil;
import com.tul.vapp.servicecenter.utils.IpHelper;
import com.tul.cusa.zookeeper.IZookeeperClient;
import com.tul.vapp.servicecenter.zookeeper.ZooKeeperClientFactory;
import org.springframework.util.CollectionUtils;

/**
 * reportRepository
 *
 * @author wujunlei
 * @since 2018/1/4
 */
public class ReportRepository {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ReportRepository.class);

    /**
     * 不合法ip
     */
    private static final String[] IP_EXCLUSION = {"127.0.0.1", "0.0.0.0", "localhost"};


    /**
     * appid
     */
    private String appId;

    /**
     * zkclient
     */
    private IZookeeperClient client;

    /**
     * ip
     */
    private String appIp;

    /**
     * constructor
     *
     * @param appId appid
     */
    public ReportRepository(String appId) {
        this.appId = appId;
        this.client = ZooKeeperClientFactory.getClient();
        initNode();
    }

    /**
     * init
     */
    private void initNode() {
        if (!client.exists(ZkNodeConstant.STATUS_NODE)) {
            client.create(ZkNodeConstant.STATUS_NODE, false);
        }
    }

    /**
     * publishStatus
     *
     * @param status status
     * @param value value
     */
    public void publishStatus(StatusEnum status, String value) {
        publishStatus(status, value, null);
    }

    /**
     * publishStatus
     *
     * @param status status
     * @param value value
     * @param appName appName
     */
    public void publishStatus(StatusEnum status, String value, String appName) {
        if (appName == null) {
            appName = this.appId;
        }
        boolean isInit = false;
        if (appIp == null) {
            if (StatusEnum.IP.getKey().equals(status.getKey())) {
                appIp = validateIp(value);
            }
            appIp = IpHelper.getHostIp();
            isInit = true;
        }

        String appStatusNode = appName + "@" + appIp;
        String path = ZkNodeConstant.STATUS_NODE + ZkNodeConstant.SEPERATEOR + appStatusNode;
        if (!client.exists(path)) {
            client.create(path, true);
        }
        byte[] content = client.getData(path);
        //转化为map，对于存在的key，进行更新，不存在的key，新增
        String contentStr = new String(content, CharSetConstant.UTF8);
        Map<String, String> contentData = null;
        contentData = ConfigUtil.format(contentStr);
        if (contentData == null) {
            return;
        }
        contentData.put(status.getKey(), value);
        if (isInit) {
            contentData.put(StatusEnum.IP.getKey(), appIp);
        }
        //将map转化为string
        String zkData = ConfigUtil.parseMapToStr(contentData);
        client.setData(path, zkData.getBytes());
    }

    /**
     * 校验Ip合法性
     * @param ip ip
     * @return 合法ip
     */
    private String validateIp(String ip) {
        if (StringUtil.isEmpty(ip) || CollectionUtils.arrayToList(IP_EXCLUSION).contains(ip)) {
            return IpHelper.getHostIp();
        } else {
            return ip;
        }
    }

}
